/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.opencvjava.practise;

import org.opencv.core.Mat;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.opencvjava.support.util.CvUtils.imshow;
import static com.opencvjava.support.util.CvUtils.mat;
import static org.opencv.imgcodecs.Imgcodecs.IMREAD_GRAYSCALE;
import static org.opencv.imgproc.Imgproc.THRESH_BINARY;
import static org.opencv.imgproc.Imgproc.threshold;

/**
 * @author : sunzb
 * @date: 2019/6/5
 */
@Service
public class Dot {

    public static final int THRESH_HOLDER = 9;

    public void test() {
        Mat gray = mat("dot.jpg", IMREAD_GRAYSCALE);
        Mat binary = new Mat();
        threshold(gray, binary, 127, 255, THRESH_BINARY);
        imshow("阈值二值化", binary);

        int rows = binary.rows();
        int cols = binary.cols();
        int total = (int) binary.total();
        byte[] data = new byte[total];
        binary.get(0, 0, data);
        long start = System.currentTimeMillis();
        List<Integer> allIndexes = new ArrayList<>();
        for (int row = 0; row < rows; row++) for (int col = 0; col < cols; col++)
            if (data[row * cols + col] == -1) {
                List<Integer> indexes = new ArrayList<>();
                dg(row, col, rows, cols, data, indexes);
                if (indexes.size() < THRESH_HOLDER) allIndexes.addAll(indexes);
            }
        for (Integer index : allIndexes) data[index] = 0;
        for (int index = 0; index < total; index++) if (data[index] == -2) data[index] = -1;
        Mat dst = new Mat(binary.size(), binary.type());
        System.out.println("during:" + (System.currentTimeMillis() - start) + "ms");
        dst.put(0, 0, data);
        imshow("结果", dst);
    }

    private void dg(int row, int col, int rows, int cols, byte[] data, List<Integer> indexes) {
        if (row < 0 || row >= rows) return;
        if (col < 0 || col >= cols) return;
        int index = row * cols + col;
        byte color = data[index];
        if (color != -1) return;
        indexes.add(index);
        data[index] = -2;
        if (indexes.size() >= 100) return;
        dg(row, col - 1, rows, cols, data, indexes);
        dg(row, col + 1, rows, cols, data, indexes);
        dg(row - 1, col - 1, rows, cols, data, indexes);
        dg(row - 1, col, rows, cols, data, indexes);
        dg(row - 1, col + 1, rows, cols, data, indexes);
        dg(row + 1, col - 1, rows, cols, data, indexes);
        dg(row + 1, col, rows, cols, data, indexes);
        dg(row + 1, col + 1, rows, cols, data, indexes);
    }
}
